﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;

public class PictureToMul4
{
    [MenuItem("Assets/资源提取/图片拓展到4的倍数")]
    public static void AssetToMul4()
    {
        foreach (var guid in Selection.assetGUIDs)
        {
            var path = AssetDatabase.GUIDToAssetPath(guid);

            if (Directory.Exists(path))
            {
                DoDir(path);
            }
            else
            {
                DoSng(path);
            }
        }
    }


    public static void DoDir(string path)
    {
        string[] files = Directory.GetFiles(path);
        int cnt = files.Length;

        for (int i = 0; i < cnt; i++)
            DoSng(files[i]);
    }

    public static void DoSng(string path)
    {
        string assPath = path;
        TextureImporter txImp = TextureImporter.GetAtPath(assPath) as TextureImporter;

        if (null == txImp) return;

        txImp.isReadable = true;
        txImp.textureFormat = TextureImporterFormat.ARGB32;
        txImp.npotScale = TextureImporterNPOTScale.None;
        AssetDatabase.ImportAsset(assPath);

        Texture2D tmpTx = AssetDatabase.LoadAssetAtPath<Texture2D>(assPath);
        int tW = tmpTx.width > tmpTx.height ? tmpTx.width : tmpTx.height;
        int u4 = tmpTx.width % 4;

        if (u4 == 0) return;
        int t4 = tmpTx.width / 4;
        tW = (t4 + 1) * 4;

        Texture2D newTex = new Texture2D(tW, tW, TextureFormat.RGBA32, false);

        for (int i = 0; i < tW; i++)
        {
            for (int y = 0; y < tW; y++)
            {
                if (i == 0 || y == 0)
                {
                    newTex.SetPixel(i, y, new Color(0, 0, 0, 0));
                    continue;
                }

                int ui = i - 1;
                int uy = y - 1;

                if (ui <= tmpTx.width && uy <= tmpTx.height)
                {
                    newTex.SetPixel(i, y, tmpTx.GetPixel(ui, uy));
                }
            }
        }

        File.WriteAllBytes(assPath, newTex.EncodeToPNG());

        txImp = TextureImporter.GetAtPath(assPath) as TextureImporter;
        txImp.isReadable = true;
        txImp.textureFormat = TextureImporterFormat.ASTC_RGBA_4x4;
        txImp.npotScale = TextureImporterNPOTScale.None;
        AssetDatabase.ImportAsset(assPath);
    }
}
